package com.tencent.hummingbird.portal.controller;


import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.pojo.Comment;
import com.tencent.hummingbird.portal.r.R;
import com.tencent.hummingbird.portal.service.ICommentService;
import com.tencent.hummingbird.portal.vo.CommentVO;
import com.tencent.hummingbird.portal.vo.UpdateCommentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Slf4j
@RestController
@RequestMapping("/portal/comment")
public class CommentController {
    @Autowired
    private ICommentService commentService;
    @PostMapping("/postcomment")
    public R<Comment> postComment(@AuthenticationPrincipal UserDetails userDetails,
                                  @RequestBody @Validated CommentVO commentVO, BindingResult result){
        if(result.hasErrors()){
            return R.invalidRequest(result.getFieldError().getDefaultMessage());
        }
        Comment comment = commentService.postComment(userDetails.getUsername(),commentVO);
        return R.created(comment);
    }
    @PostMapping("/updateComment")
    public R updateComment(@RequestBody @Validated UpdateCommentVO updateCommentVO,BindingResult result){

        if(result.hasErrors()){
            return R.invalidRequest(result.getFieldError().getDefaultMessage());
        }
        commentService.updateComment(updateCommentVO.getId(),updateCommentVO.getContent());
        return R.created("修改成功");
    }
    @GetMapping("/delete/{commentId}")
    public R deleteComment(@AuthenticationPrincipal UserDetails user,@PathVariable Integer commentId){
        if(commentId==null || commentId<1){
            return R.invalidRequest("commentId不能为空");
        }
        commentService.removeComment(user.getUsername(),commentId);
        return R.ok("删除成功");
    }
}
